package string;

import java.util.HashSet;
import java.util.Set;

//https://leetcode.cn/problems/wtcaE1/
//给定一个字符串 s ，请你找出其中不含有重复字符的 最长连续子字符串 的长度。
public class LCR_016无重复字符的最长子串 {
    public static int lengthOfLongestSubstring(String s) {
        char[] arr = s.toCharArray();
        int len = arr.length;
        Set<Character> set = new HashSet<>();
        int count = 0,maxLength = 0;
        int left = 0;
        for(int right=0; right<len; right++){
            while (set.contains(arr[right])){
                set.remove(arr[left++]);
            }
            set.add(arr[right]);
            maxLength = Math.max(maxLength,right-left+1);
        }
        return maxLength;
    }
    //变式：找出那个最长的字符串
    public static String Substring(String s) {
        char[] arr = s.toCharArray();
        int len = arr.length;
        Set<Character> set = new HashSet<>();
        int count = 0,maxLength = 0,left = 0,start = 0;
        for(int right=0; right<len; right++){
            while (set.contains(arr[right])){
                set.remove(arr[left++]);
            }
            set.add(arr[right]);
            if (right - left + 1 > maxLength) {
                maxLength = right - left + 1;
                start = left;
            }
        }
        return s.substring(start,start + maxLength);
    }
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb")); // 输出 3
        System.out.println(lengthOfLongestSubstring("dvdf")); // 输出 3
        System.out.println(lengthOfLongestSubstring("pwwkew")); // 输出 3
        System.out.println(lengthOfLongestSubstring("")); // 输出 0
        System.out.println(lengthOfLongestSubstring("abcdefg")); // 输出 7
        System.out.println(Substring("abcabcbb")); // 输出 3
        System.out.println(Substring("dvdf")); // 输出 3
        System.out.println(Substring("pwwkew")); // 输出 3
        System.out.println(Substring("")); // 输出 0
        System.out.println(Substring("abcdefg")); // 输出 7
    }
}
